import React from 'react';
import { BrowserRouter as Router, Route, Routes, useParams, useNavigate } from 'react-router-dom';
import UnitListPage from './pages/UnitList';
import UnitDetailPage from './pages/UnitDetail';
import UnitConfigPage from './pages/UnitConfig';
import UnitInfo from './pages/UnitDetail/UnitInfo';
import MetricsAnalysis from './pages/MetricsAnalysis';
import ApplicationDetail from './pages/MetricsAnalysis/ApplicationDetail';
import ScanManagement from './pages/SaManagement/ScanManagement';
import { UserContext } from './context/UserContext';
import Sidebar from './pages/UnitList/Sidebar';
import Topbar from './pages/UnitList/Topbar';
import { Layout } from 'antd';

const { Sider, Content } = Layout;

const MainLayout: React.FC<{ children: React.ReactNode }> = ({ children }) => (
  <Layout style={{ height: '100vh', overflow: 'hidden' }}>
    <Sider width={160} style={{ background: '#fff', overflow: 'auto' }}>
      <Sidebar />
    </Sider>
    <Layout style={{ height: '100%', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
      <Topbar />
      <Content style={{ flex: 1, minHeight: 0, overflow: 'hidden' }}>{children}</Content>
    </Layout>
  </Layout>
);

const App: React.FC = () => {
  const user = { name: 'demo', permissions: ['unit:view'] };

  return (
    <UserContext.Provider value={{ user }}>
      <Router>
        <Routes>
          <Route path="/units" element={<MainLayout><UnitListPage /></MainLayout>} />
          <Route path="/metrics" element={<MainLayout><MetricsAnalysis /></MainLayout>} />
          <Route path="/metrics/applications/:appId" element={<MainLayout><ApplicationDetail /></MainLayout>} />
          <Route path="/unit/create" element={<MainLayout><UnitConfigPage mode="create" /></MainLayout>} />
          <Route path="/unit/:unitId/edit" element={<MainLayout><UnitConfigPageWrapper /></MainLayout>} />
          <Route path="/unit/:unitId/info" element={<MainLayout><UnitInfoWrapper /></MainLayout>} />
          <Route path="/unit/:unitId" element={<MainLayout><UnitDetailPageWrapper /></MainLayout>} />
          <Route path="/sa/scan-management" element={<MainLayout><ScanManagement /></MainLayout>} />
        </Routes>
      </Router>
    </UserContext.Provider>
  );
};

// 包装一下，提取unitId参数传递给UnitDetailPage
const UnitDetailPageWrapper = () => {
  const { unitId } = useParams();
  return <UnitDetailPage unitId={unitId || ''} />;
};

// 包装，提取unitId参数传递给UnitConfigPage（编辑模式）
const UnitConfigPageWrapper = () => {
  const { unitId } = useParams();
  return <UnitConfigPage mode="edit" unitId={unitId} />;
};

// 包装，提取unitId参数传递给UnitInfo
const UnitInfoWrapper = () => {
  const { unitId } = useParams();
  const navigate = useNavigate();

  if (!unitId) {
    return <div>单元ID无效</div>;
  }

  return <UnitInfo unitId={unitId} onEdit={() => navigate(`/unit/${unitId}/edit`)} />;
};

export default App;
